<template>
  <div>
    <div
      :class="{ fullscreen: fullscreen }"
      :style="{ width: containerWidth }"
      class="tinymce-container"
    >
      <textarea :id="tinymceId" class="tinymce-textarea" />
    </div>
    <div ref="showTextarea" style="display: none" />
  </div>
</template>

<script>
import fontFamily from "./fontFamily";
import plugins from "./plugins";
import toolbar from "./toolbar";
import load from "./dynamicLoadScript";
import { getSTSToken } from "@/api/service/upload";

// import { uploadFile } from '@/api/editor/editor'
const prefix = process.env.NODE_ENV === "production" ? "" : "";

// const tinymceCDN =   'https://cdn.jsdelivr.net/npm/tinymce@6.4.1/tinymce.min.js' 
 prefix + "/static/tinymce/tinymce.min.js";
// 'https://cdn.jsdelivr.net/npm/tinymce@6.4.1/tinymce.min.js' //

export default {
  name: "Tinymce",
  props: {
    id: {
      type: String,
      default: function() {
        return (
          "vue-tinymce-" +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + "")
        );
      }
    },
    value: {
      type: String,
      default: ""
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      }
    },
    plugins: {
      type: Boolean,
      required: false,
      default() {
        return false;
      }
    },
    menubar: {
      type: String,
      default: "file edit insert view format table "
    },
    height: {
      type: [Number, String],
      required: false,
      default: "auto"
    },
    width: {
      type: [Number, String],
      required: false,
      default: "auto"
    },
    // uPImgCallback: Object,
    readonly: Boolean
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        en: "en",
        zh: "zh_CN",
        es: "es_MX",
        ja: "ja"
      },
      uPImgCallback: {}, // 图片回调数据
      showTextareaHtml: "", // 富文本中需要提交的内容
      imgUrl: "", // 回显示的图片流
      STSTokenData: {} // 阿里云 oss
    };
  },
  computed: {
    containerWidth() {
      const width = this.width;
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`;
      }
      return width;
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() =>
          window.tinymce.get(this.tinymceId).setContent(val || "")
        );
      }
    }
  },
  mounted() {
    debugger
    this.init();
    this.getSTSTokenFun();
  },
  activated() {
    if (window.tinymce) {
      this.initTinymce();
    }
  },
  deactivated() {
    this.destroyTinymce();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    // 获取ststoken及相应参数
    getSTSTokenFun() {
      getSTSToken().then(res => {
        if (res.code == 200) {
          this.STSTokenData = res.data;
        }
      });
    },
    imgTagAddStyle(htmlstr) {
      // 正则匹配所有img标签
      // var regex0 = new RegExp("(i?)(\<img)([^\>]+\>)","gmi");
      // 正则匹配不含style="" 或 style='' 的img标签
      // eslint-disable-next-line no-useless-escape
      var regex1 = new RegExp(
        "(i?)(<img)(?!(.*?style=['\"](.*)['\"])[^>]+>)",
        "gmi"
      );
      // 给不含style="" 或 style='' 的img标签加上style=""
      htmlstr = htmlstr.replace(regex1, '$2 style=""$3');
      // console.log('增加style=""后的html字符串：' + htmlstr)
      // 正则匹配含有style的img标签
      // eslint-disable-next-line no-useless-escape
      var regex2 = new RegExp("(i?)(<img.*?style=['\"])([^>]+>)", "gmi");
      // 在img标签的style里面增加css样式(这里增加的样式：display:block;max-width:100%;height:auto;border:5px solid red;)
      htmlstr = htmlstr.replace(regex2, "$2max-width:100%;height:auto;$3");
      return htmlstr;
    },
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, err => {
        if (err) {
          this.$message.error(err.message);
          return;
        }
        this.initTinymce();
      });
    },
    initTinymce() {
      const _this = this;
      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        language: "zh_CN",
        height: this.height,
        body_class: "panel-body ",
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        plugins: this.plugins ? this.plugins : plugins,
        font_formats: fontFamily,
        fontsize_formats:
          "8pt 10pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 28pt 30pt 32pt 34pt 36pt 40pt 46pt 50pt 60pt 80pt 100pt",
        end_container_on_empty_block: true,
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: "square",
        readonly: this.readonly,
        advlist_number_styles: "default",
        imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
        default_link_target: "_blank",
        link_title: false,
        automatic_uploads: true,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            editor.setContent(_this.value);
          }
          _this.hasInit = true;
          editor.on("NodeChange Change KeyUp SetContent", () => {
            this.hasChange = true;
            this.$emit("input", editor.getContent());
          });
        },
        setup(editor) {
          editor.on("FullscreenStateChanged", e => {
            _this.fullscreen = e.state;
          });
        },
        images_upload_handler: (blobInfo, success, failure, progress)=> {
          // console.log("blobInfo")
          console.log(blobInfo);
          // 方案一：base64的存储
          // console.log(blobInfo.base64())
          // 获取base64图片大小，返回KB数字
          // var strLength = blobInfo.base64().length
          // var fileLength = parseInt(strLength - (strLength / 8) * 2)
          // 由字节转换为KB
          // var base64Info = 'data:image/jpeg;base64,' + blobInfo.base64()
          // success(base64Info)

          // 方案二：阿里云 OSS
          let file = blobInfo.blob();
          console.log(file);
          // 这里是OSS，需要配置oss
          const client = new OSS.Wrapper({
            // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
            region: "oss-cn-shanghai",
            // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
            accessKeyId: this.STSTokenData.AccessKeyId,
            accessKeySecret: this.STSTokenData.AccessKeySecret,
            stsToken: this.STSTokenData.SecurityToken,
            endpoint: "https://" + "oss-accelerate.aliyuncs.com", // 拼上https防止跨域
            // 填写Bucket名称。
            bucket: "whaleyunxun-werich",
            secure: true,
            // cname: true
          });
          var f = file;
          const Name = f.name;
          const suffix = Name.substr(Name.indexOf("."));
          const time = "";
          const storeAs = "WhaleMall/web-richText-imgs/" + time + Name; // 路径+时间戳+后缀名
          // multipartUpload 分片上传
          client
            .multipartUpload(storeAs, f)
            .then(result => {
              let aliUrl = result.res.requestUrls;
              console.log(aliUrl); //这就是阿里云返回的url
              let domainName = "https://whaleyunxun-werich.oss-accelerate.aliyuncs.com";
              const url = `${domainName}/${storeAs}`;
              success(url);
            })
            .catch(function(err) {
              console.log(err);
            });
        },
        // 粘贴事件
        paste_postprocess: function(plugin, args) {
          console.log("args")
          console.log(args)
          let imageArray = []
          args.content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
            imageArray.push(capture)
          })
          console.log(imageArray)
          console.log(fragment.node)
          var textnode = document.createTextNode("Added Text");
          fragment.node.appendChild(textnode);
          var textnode = document.createTextNode("<img src='"+_this.imgUrl+"'>");
          fragment.node.appendChild(textnode);
        },
        end_container_on_empty_block: true,
        powerpaste_word_import: "propmt", // 参数可以是propmt, merge, clear，效果自行切换对比
        powerpaste_html_import: "propmt", // propmt, merge, clear
        powerpaste_block_drop: false,
        powerpaste_allow_local_images: true, // 是否支持复制本地图片true:支持
        paste_word_valid_elements: "*[*]", // word需要它
        paste_data_images: false, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        paste_convert_word_fake_lists: false, // 插入word文档需要该属性
        paste_as_text: false, // 控制是否带格式粘贴文本false:支持带格式
        // 添加扩展插件
        external_plugins: {
          powerpaste: "/static/tinymce/plugins/powerpaste/plugin.js"
          // powerpaste: '/manage/static/tinymce/plugins/powerpaste/plugin.js', // 二级目录部署配置
        }
      });
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId);
      if (this.fullscreen) {
        tinymce.execCommand("mceFullScreen");
      }

      if (tinymce) {
        tinymce.destroy();
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
    showTinymce() {
      var contentHTMl = this.$refs.showTextarea;
      this.showTextareaHtml = window.tinymce.get(this.tinymceId).getContent();
      contentHTMl.innerHTML = this.showTextareaHtml;
      return this.imgTagAddStyle(contentHTMl.innerHTML);

      // return contentHTMl.innerHTML
    }
    // 图片解析
    // handleImgs(fileName) {
    //   showImg(fileName)
    //     .then(response => {
    //       console.log("图片流");
    //       console.log(response);
    //       let blob = response.data;
    //       this.imgUrl=blob;

    //     })
    //     .catch(e => {
    //       console.log(e);
    //     });
    // }
  },
  setup(props, ctx) {
    const getTinymceHTML = () => {
      // let txt = window.tinymce.get(props.id).getContent();
      // return txt;

      let htmlstr = window.tinymce.get(props.id).getContent();
      var regex1 = new RegExp(
        "(i?)(<img)(?!(.*?style=['\"](.*)['\"])[^>]+>)",
        "gmi"
      );
      htmlstr = htmlstr.replace(regex1, '$2 style=""$3');
      var regex2 = new RegExp("(i?)(<img.*?style=['\"])([^>]+>)", "gmi");
      htmlstr = htmlstr.replace(regex2, "$2max-width:100%;height:auto;$3");
      return htmlstr;
    };
    return {
      getTinymceHTML
    };
  }
};
</script>
<style lang="scss">
.tox-tinymce-aux {
  z-index: 8888 !important;
  .tox .tox-dialog-wrap__backdrop {
    z-index: 9999 !important;
  }
}
.mce-branding {
  display: none !important;
}
.mce-wordcount {
  margin-right: 20px !important;
}
.mce-flow-layout {
  padding: 5px 0 !important;
}
.mce-stack-layout .mce-menu-item:nth-child(3) {
  display: none;
}
</style>

<style scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}
.tinymce-container :deep(.mce-fullscreen) {
  z-index: 10000;
}
.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}
.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}
.editor-upload-btn {
  display: inline-block;
}
body .mce-notification-error {
  display: none !important;
}
</style>
